/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.github.xiaoymin.deploy.plugin.impl;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
import com.github.xiaoymin.deploy.common.PluginConst;
import com.github.xiaoymin.deploy.model.DeployRequest;
import com.github.xiaoymin.deploy.plugin.DeployService;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 将本地文件上传至目标服务器
 * @since:deploy-helper 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2020/07/05 13:43
 */
public class UploadService implements DeployService {

    Logger logger= LoggerFactory.getLogger(UploadService.class);

    @Override
    public boolean action(DeployRequest deployRequest) {
        logger.info("UploadService Run...");
        //开始上传本地jar文件
        try {
            deployRequest.getConnection().upload(buildSourceFile(deployRequest.getHelperDeploy().getSource(),deployRequest.getMavenProject()),deployRequest.getHelperDeploy().getTarget());
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getPluginName() {
        return PluginConst.PLUGIN_UPLOAD_SERVICE;
    }

    /**
     * 构建目标sourceFile
     * @param source 源文件
     * @return 根据操作系统构建的目录
     */
    private String buildSourceFile(String source, MavenProject mavenProject){
        StringBuilder stringBuilder=new StringBuilder();
        String windows="\\w+:.*";
        //判断source是否是根目录,如果不是根目录,则将目前项目目录append
        if (StrUtil.startWith(source,PluginConst.ROOT_PREFIX)|| ReUtil.isMatch(windows,source)){
            //根目录
            stringBuilder.append(source);
        }else{
            stringBuilder.append(mavenProject.getBasedir().getAbsolutePath()).append(File.separator);
            //判断是否windows
            logger.info("system:{}", SystemUtil.getOsInfo().getName());
            if (StrUtil.containsIgnoreCase(SystemUtil.getOsInfo().getName(),"windows")){
                //当前系统是windows,替换/的字符
                stringBuilder.append(StrUtil.replace(source,"/","\\"));
            }else{
                stringBuilder.append(source);
            }
        }
        return stringBuilder.toString();
    }
}
